package com.googlecode.intellimars.mrsp;

import com.googlecode.intellimars.mrsp.tableview.ArtifactListTableView;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.net.HttpConfigurable;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;

public class MavenRepoSearchView {
    private static Logger LOG = Logger.getInstance("mrsp");

    private JPanel mainPanel;
    private JComboBox typeCombo;
    private JTextField queryText;
    private ArtifactListTableView table;
    private JButton searchButton;

    private boolean isSearching;

    public MavenRepoSearchView() {
        queryText.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (KeyEvent.VK_ENTER == e.getKeyCode()) {
                    doSearch();
                }
            }
        });
        searchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                doSearch();
            }
        });
    }

    public JPanel getMainPanel() {
        return mainPanel;
    }

    private void doSearch() {
        if (queryText.getText().length() < 2 || isSearching) {
            return;
        }

        try {
            HttpConfigurable.getInstance().prepareURL("http://maven.ozacc.com/");
        }
        catch (IOException e) {
            LOG.error(e);
            JOptionPane.showMessageDialog(mainPanel, "The unexpected error happened!!",
                                          MaveRepoSearchPlugin.TOOL_WINDOW_ID,
                                          JOptionPane.ERROR_MESSAGE);
        }

        Runnable searchTask = new Runnable() {
            public void run() {
                isSearching = true;
                queryText.setEditable(false);
                searchButton.setEnabled(false);

                String keyword = queryText.getText();
                String type = typeCombo.getSelectedItem().toString();
                table.search(keyword, type);

                searchButton.setEnabled(true);
                queryText.setEditable(true);
                isSearching = false;
            }
        };
        Thread t = new Thread(searchTask);
        t.start();
    }

}
